<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/static/layui/css/layui.css"  media="all">
    <title>弈秋</title>
</head>

<body>
    

        <div class="layui-fluid">
            <div class="layui-row layui-col-space15">   
                <div class="layui-col-md9">
                    <div class="layui-card">
                        <div class="layui-card-header">
                            弈秋对战平台
                        </div>
                        <div style="background: rgb(248, 204, 179);">
                            <canvas style="border:solid 2px red;margin: 50px;" id="can"></canvas>
                            <div id="ts" style="font-size: 50px;display: none;"></div>
                        </div>                        
                    </div>
                </div>
                <div class="layui-col-md3">
                    <div class="layui-card">
                        <div class="layui-btn-group">
                            <button id="regret_btn" type="button" class="layui-btn layui-btn-primary layui-btn-sm">悔棋</button>
                            <button id="save_btn" type="button" class="layui-btn layui-btn-primary layui-btn-sm">存档</button>
                            <button id="load_btn" type="button" class="layui-btn layui-btn-primary layui-btn-sm">读档</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!--该  div 下放置本网页需要用到的各种表单-->
        <div>
            <!--游戏配置表单-->
            <div class="layui-card" id="yiqiu_set"  style="display: none;">
                <div class="layui-card-header">
                  对局设置
                </div>
                <div class="layui-card-body" pad15>
                  
                    <form class="layui-form" lay-filter="SetOfGame">
                        <div class="layui-form-item">
                            <div class="layui-input-inline">
                                <div class="layui-form-mid layui-word-aux">棋种</div>
                            </div>
                            <div class="layui-input-inline">
                                <select id="chess_type" name="chess_type" lay-filter="chess_type">
                                    <option value="0">五子棋</option>
                                    <option value="1">围棋</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-input-inline">
                                <div class="layui-form-mid layui-word-aux">棋盘尺寸</div>
                            </div>
                            <div class="layui-input-inline">
                                <select id="chess_board_size" name="chess_board_size" lay-filter="chess_board_size">
                                    <option value="15"> 15 乘 15 </option>
                                    <option value="19"> 19 乘 19 </option>
                                </select>
                            </div>
                        </div>
                        
                        {% csrf_token %}
                    </form>
                  
                </div>
            </div>
            <!--现有存档选择表单-->
            <form style="display: none;" class="layui-form" id="Select_Mementos_Form" lay-filter="Select_Mementos_Form">
                <div class="layui-form-item" pane>
                    <label class="layui-form-label">存档选择</label>
                    <div class="layui-input-block">
                        <select id="current_mementos" name="current_mementos" lay-filter="current_mementos">
                            {% for memento in memento_list %}
                            <option value="{{memento.index}}">{{memento.description}}</option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
                {% csrf_token %}
            </form>
            <!--新存档创建表单-->
            <form  style="display: none;" class="layui-form" id="Create_Mementos_Form" lay-filter="Create_Mementos_Form">
                <div class="layui-form-item" pane>
                    <label class="layui-form-label">存档描述</label>
                    <div class="layui-input-block">
                        <input type="text" name="memento_description" value="" placeholder="能帮助你区分本次对局的关键信息，规则、棋盘尺寸等" autocomplete="off" class="layui-input">
                    </div>
                </div>
                {% csrf_token %}
            </form>
        </div>
    
<script src="/static/layui/layui.js" charset="utf-8"></script>

<script>     
    layui.config({
        base:'static/layui/'
    }).extend({
        notice: 'custom/notice/notice'
    }).use(['layer', 'element', 'form', 'notice'], function(){
        var $=layui.$
            ,element=layui.element
            ,form=layui.form
            ,layer=layui.layer
            ,notice=layui.notice;

        const csrf = $('input[name="csrfmiddlewaretoken"]').val();

        
        /*游戏设置*/
        var GameSet = {
            'chess_type': '0', // 0 为五子棋，1 为围棋
            'chess_board_size': '15', 
        }
        // /*将初始游戏设置载入表单*/ TODO 该方法暂时有一些问题，故需手动保证 GameSet 初始值与表单中默认值一致
        // form.val('SetOfGame', GameSet)
        /*配置游戏设置的相关表单项的监听*/
        form.on('select(chess_type)', function (obj) {GameSet['chess_type']=obj.value; console.log(GameSet)});
        form.on('select(chess_board_size)', function (obj) {GameSet['chess_board_size']=obj.value; console.log(GameSet)});

        
        notice.info("提示信息：所有的告警消息都会实时推送至此");
        function ChessBoard(game_uuid, row_num, col_num, function_receive_click){
            // function_receive_click 为点击棋盘事件发生时的回调函数,该函数需要给出对应坐标需要下哪个颜色的子，例: function(x,y){... return 1;}
            var color_pallete = ["green","black","white"];//颜色数组,0为无棋子,1为黑,2为白
            var uuid = game_uuid
            var r_n = row_num; //棋盘的横线数
            var c_n = col_num; //棋盘的竖线数
            var qiju = []      //储存棋子位置的变量
            var board_canvas = document.getElementById("can");
            board_canvas.height = (r_n * 40);
            board_canvas.width = (c_n * 40);
            var board_canvas_2d = board_canvas.getContext("2d");
            var game_over_flag = false;
            var black_flag = true;

            function render(){
                board_canvas_2d.clearRect(0, 0, board_canvas.width, board_canvas.height);
                for(var y = 0;y < r_n;y++){
                    for (var x = 0; x < c_n; x++){
                        if(y <r_n-1 && x < c_n-1){//
                            board_canvas_2d.strokeStyle = "black";//设置格子的颜色
                            //绘制每个格子的位置，因为画布比棋盘大40像素，我们要把棋盘居中就需要在XY上面加20像素-
                            board_canvas_2d.strokeRect(x * 40 + 20,y * 40 + 20,40,40);
                        }
                        if(qiju[y][x] != 0){
                            board_canvas_2d.beginPath();
                            board_canvas_2d.arc((x * 40) + 20, (y * 40) + 20 ,r_n ,0,2 * Math.PI);
                            board_canvas_2d.shadowBlur=10;
                            board_canvas_2d.shadowOffsetX=5;
                            board_canvas_2d.shadowOffsetY=5;
                            board_canvas_2d.shadowColor="#747371";
                            board_canvas_2d.fillStyle = color_pallete[qiju[y][x]];
                            board_canvas_2d.fill();
                            board_canvas_2d.shadowBlur=0;
                            board_canvas_2d.shadowOffsetX=0;
                            board_canvas_2d.shadowOffsetY=0;
                            board_canvas_2d.shadowColor="black";
                        }
                    }
                }
            }

            function reset(){
                // 初始化 棋局状态
                qiju = [];
                game_over_flag = false;
                black_flag = true;
                for(var y = 0;y < r_n; y++){
                    qiju.push([]);//在数组里面添加数组以充当Y轴
                    for (var x = 0; x < c_n; x++) {
                        qiju[y].push(0);//在二维数组里面添加棋子，0是空，1是黑棋，2是白棋
                    }
                }
            }
            reset();

            // 绑定点击事件，事件发生时给回调函数传递所点击的棋盘坐标
            on_click_processing = false;
            board_canvas.onclick = function(e){
                // 如果已经有一个点击事件正在处理了，就退出，因为我们点击事件的处理过程涉及到前后端交互可能会很慢
                if(on_click_processing){return}
                on_click_processing = true
                if(game_over_flag){return;}
                // console.log(e);
                var Y = parseInt(e.offsetY / 40);
                var X = parseInt(e.offsetX / 40);
                
                // 向后端发起请求，走一步
                $.ajax({
                    url:"/game/make_a_move/",
                    type:"post",
                    data: {
                        "game_uuid": uuid
                        ,"position_row": Y
                        ,"position_col": X
                        ,"csrfmiddlewaretoken": csrf
                    },
                    async: false,
                    success:function (raw_data) {
                        data = JSON.parse(raw_data);
                        // console.log(data);
                        if(data["code"]===0){
                            actual_data = data["data"];
                            // 1. 先渲染棋局
                            qiju = actual_data['board'];
                            render();
                            // 2. 再判定游戏是否接受
                            if(actual_data['has_winner']){
                                switch(actual_data['winner_index']){
                                    case 0:
                                        notice.info('对局结束，平局')
                                        layer.alert('平局')
                                        break;
                                    case 1:
                                        notice.info('对局结束，黑胜')
                                        layer.alert('黑胜')
                                        break;
                                    case 2:
                                        notice.info('对局结束，白胜')
                                        layer.alert('白胜')
                                        break;
                                }
                                game_over_flag = true
                            }
                            
                            black_flag = !black_flag;
                        } else {
                            notice.error(data["message"])
                        }
                    },
                    error:function (err) {
                        notice.error("创建对局过程中后端处理异常")
                    }
                                            
                });


                // // chess_type = function_receive_click(X,Y);
                // qiju[Y][X] = black_flag?1:2;
                // render();
                on_click_processing = false;
            }
            
            board_canvas.onmousemove = function(e){
                if(game_over_flag){return;}
                // console.log(e.offsetY, e.offsetX)
                var Y = parseInt(e.offsetY / 40);
                var X = parseInt(e.offsetX / 40);
                if(Y<r_n && Y>=0 && X<c_n && X>=0 && qiju[Y][X] == 0){
                    if(black_flag){
                        qiju[Y][X] = 1;
                    } else {
                        qiju[Y][X] = 2;
                    }
                    render();
                    qiju[Y][X] = 0;
                }
            }
            return {
                Restart: function(){
                    reset();
                    render(); //绘制棋盘
                },
                GetUUID: function(){
                    return uuid;
                },
                SetUID: function(new_uuid){
                    uuid = new_uuid;
                },
                // SetTurn: function(index){ index==0?black_flag=true:black_flag=false};
                BlackTurn: function(){return black_flag},
                SetQiJu: function(board_array, change_black_flag=false){
                    qiju = board_array;
                    if(change_black_flag){
                        black_flag = !black_flag
                    }
                    render();
                },
            }
        }

        var ChessBoard_GlobalInstance = ChessBoard(15,15);
        $("#regret_btn").click(function(){
            // 向后端发起请求，后端判定通过之后返回上一个局面的数据
            $.ajax({
                url:"/game/regret/",
                type:"post",
                data: {
                    "game_uuid": ChessBoard_GlobalInstance.GetUUID()
                    ,"csrfmiddlewaretoken": csrf
                },

                success:function (raw_data) {
                    data = JSON.parse(raw_data);
                    console.log(data);
                    if(data["code"]===0){
                        console.log(data["data"])
                        ChessBoard_GlobalInstance.SetQiJu(data["data"]["board"], true);
                        notice.info('response_from_backend: '+data['message'])
                        layer.msg("悔棋成功！")
                    }
                    else{
                        notice.error("悔棋失败\n"+data['message']);
                        layer.alert("悔棋失败\n"+data['message']);
                    }
                },
                error:function (err) {
                    notice.error("悔棋过程中后端处理异常")
                }
                                            
            });
        });
        $("#save_btn").click(function(){
            var save_layer=layer.open({
                type: 1,
                skin: 'layui-layer-demo', //样式类名
                closeBtn: 0, //不显示关闭按钮
                anim: 2,
                title: "新建存档文件",
                shadeClose: false, //开启遮罩关闭
                content: $('#Create_Mementos_Form'),
                btn: ["确定","取消"],
                btn1: function(){
                    //提交请求
                    $.ajax({
                        url:"/game/memento/save/",
                        type:"post",
                        async: false,
                        data: {
                            "game_uuid": ChessBoard_GlobalInstance.GetUUID()
                            ,"memento_description": form.val("Create_Mementos_Form")['memento_description']
                            ,"csrfmiddlewaretoken": csrf
                        },
                        success:function (raw_data) {
                            data = JSON.parse(raw_data);
                            console.log(data);
                            if(data["code"]===0){layer.msg("存档成功");notice.info(data["message"]);}
                            else{layer.alert("存档失败\n"+data["message"]);notice.error(data["message"]);}
                        },
                        error:function (err) {
                            notice.error("存档失败，前后端通信异常");
                        }
                                
                    });
                    layer.close(save_layer);
                } 
                ,btn2: function(){
                    console.log("取消");
                    return true;
                }   
            })
            
        })
        $("#load_btn").click(function(){
            Select_A_Memento();
        })


        function Create_A_Game(){
            var GameCreaterLayer = layer.tab({
                area: ['60%','80%'],
                closeBtn: 0, //不显示关闭按钮
                shade: 0,
                tab: [{
                title: '&nbsp;&nbsp;<i class="layui-icon layui-icon-set"></i>&nbsp;&nbsp;', 
                content: $('#yiqiu_set').html()
                }],
                btn: ["确认","返回上一级"],
                btn1: function(){
                    // 向后端发起请求，创建对应的棋局
                    $.ajax({
                        url:"/game/create/",
                        type:"post",
                        data: {
                            "game_type": GameSet['chess_type']
                            ,"row_num": GameSet['chess_board_size']
                            ,"col_num": GameSet['chess_board_size']
                            ,"csrfmiddlewaretoken": csrf
                        },

                        success:function (raw_data) {
                            data = JSON.parse(raw_data);
                            console.log(data);
                            if(data["code"]===0){
                                layer.msg("接收到后端数据，开始渲染页面");
                                uuid = data["data"];
                                ChessBoard_GlobalInstance = ChessBoard(
                                    uuid,
                                    GameSet['chess_board_size'], 
                                    GameSet['chess_board_size']
                                ); //创建新棋局
                                ChessBoard_GlobalInstance.Restart();
                                layer.close(GameCreaterLayer);
                                layer.msg("渲染完毕，对局开始！")
                            }
                            else{
                                notice.error("创建对局失败\n"+data['message'])
                            }
                        },
                        error:function (err) {
                            notice.error("创建对局过程中后端处理异常")
                        }
                                            
                    });
                },
                btn2: function(){
                    Welcome();
                    layer.close(GameCreaterLayer);
                }
            }); 
            
            form.render();
        }

        function Select_A_Memento(){
            var select_layer=layer.open({
                type: 1,
                skin: 'layui-layer-demo', //样式类名
                closeBtn: 0, //不显示关闭按钮
                anim: 2,
                title: "选择读档文件",
                shadeClose: false, //开启遮罩关闭
                content: $('#Select_Mementos_Form'),
                btn: ["确定","取消"],
                btn1: function(){
                    //提交请求
                    $.ajax({
                        url:"/game/memento/load/",
                        type:"post",
                        async: false,
                        data: {
                            "game_uuid": ChessBoard_GlobalInstance.GetUUID()
                            ,"memento_index": form.val("Select_Mementos_Form")['current_mementos']
                            ,"csrfmiddlewaretoken": csrf
                        },
                        success:function (raw_data) {
                            data = JSON.parse(raw_data);
                            console.log(data);
                            if(data["code"]===0){
                                ChessBoard_GlobalInstance = ChessBoard(
                                    ChessBoard_GlobalInstance.GetUUID(),
                                    data['data']['row_num'],
                                    data['data']['col_num'],
                                ); //创建新棋局
                                ChessBoard_GlobalInstance.SetQiJu(data["data"]["board"], data['data']['current_turn']==1?false:true);
                                notice.info('response_from_backend: '+data['message'])
                                layer.msg("读档成功！")
                            }
                            else{layer.alert("读档失败\n"+data["message"]);notice.error(data["message"]);}
                        },
                        error:function (err) {
                            notice.error("读档失败，前后端通信异常");
                        }
                                
                    });
                    layer.close(select_layer)
                } 
                ,btn2: function(){
                    console.log("取消");
                    return true;
                }   
            })
        }

        function Welcome(){
            var welcome_layer = layer.open({
                type: 1 //此处以iframe举例
                ,title: '欢迎来到弈秋对战平台'
                ,area: ['60%',]
                ,shade: 0
                ,content: '<div style="padding: 15px;"><blockquote class="layui-elem-quote layui-quote-nm">'+
                    '弈秋，通国之善弈者也。使弈秋诲二人弈，其一人专心致志，惟弈秋之为听；一人虽听之，一心以为有鸿鹄将至，思援弓缴而射之。虽与之俱学，弗若之矣。为是其智弗若与？曰：非然也。<br/>'+
                    '——《孟子 告子上》</blockquote></div>'
                
                ,btn: ['新建对局', '加入已有对局', '残局载入'] //只是为了演示
                ,btn1: function(){
                    Create_A_Game();
                    layer.close(welcome_layer);  
                }
                ,btn2: function(){
                    notice.error('功能待完成');
                    return false;
                }
                ,btn3: function(){
                    notice.error('功能待完成');
                    return false;
                }
                
                ,zIndex: layer.zIndex //重点1
                ,success: function(layero, index){
                layer.setTop(layero); //重点2. 保持选中窗口置顶
                
                //记录索引，以便按 esc 键关闭。事件见代码最末尾处。
                layer.escIndex = layer.escIndex || [];
                layer.escIndex.unshift(index);
                //选中当前层时，将当前层索引放置在首位
                layero.on('mousedown', function(){
                    var _index = layer.escIndex.indexOf(index);
                    if(_index !== -1){
                    layer.escIndex.splice(_index, 1); //删除原有索引
                    }
                    layer.escIndex.unshift(index); //将索引插入到数组首位
                });
                }
                ,end: function(){
                //更新索引
                if(typeof layer.escIndex === 'object'){
                    layer.escIndex.splice(0, 1);
                }
                }
            });
        }

        layer.ready(function(){
            Welcome();
            // ChessBoard_GlobalInstance = ChessBoard('1',15,15); //创建新棋局
            // ChessBoard_GlobalInstance.Restart();
        });
    
    });
        

    
</script>


</body>
</html>
